<?php   

class Visits_Model_DbTable_Visits extends Engine_Db_Table
{
  protected $_rowClass = 'Visits_Model_Visit';


  public function getVisits(User_Model_User $user)
  {
    $select = $this->select()
      ->where('profile_id = ?', $user->getIdentity())
      ->where('user_id > ?', 0)
      ->order('visit_date DESC')
      ;
    
    return Zend_Paginator::factory($select);
  }
  
  public function getNotifications(User_Model_User $user)
  {
    $select = $this->select()
      ->where('profile_id = ?', $user->getIdentity())
      ->where('user_id > ?', 0)
      ->where('visit_date > ?', date("Y-m-d H:i:s", strtotime("-5 minutes")))
      ->where('visit_read = ?', 0)
      ->order('visit_date DESC')
      ;
    
    return Zend_Paginator::factory($select);
  }

  public function getVisitsByMe(User_Model_User $user)
  {
    $select = $this->select()
      ->where('user_id = ?', $user->getIdentity())
      ->where('profile_id > ?', 0)
      ->order('visit_date DESC')
      ;
    
    return Zend_Paginator::factory($select);
  }

    public function markVisitasRead($visit_id)
  {
    $viewer = Engine_Api::_()->user()->getViewer();        
    $row = $this->fetchRow(array(
      'visit_id = ?' => $visit_id,
      'profile_id = ?' => $viewer->getIdentity(),
    ));
    $row->visit_read = 1;
    $row->save();
  }

  public function addVisit(User_Model_User $user)
  {
    $viewer = Engine_Api::_()->user()->getViewer();

    $row = $this->fetchRow(array(
      'user_id = ?' => $viewer->getIdentity(),
      'profile_id = ?' => $user->getIdentity(),
    ));

    if( null === $row ) {
      $row = $this->createRow();
      $row->setFromArray(array(
        'user_id' => $viewer->getIdentity(),
        'profile_id' => $user->getIdentity(),
        'visit_date' => date("Y-m-d H:i:s"),
        'visit_count' => "1",
      ));
    } else {
    $row->visit_read = 0;
    $row->visit_date = date("Y-m-d H:i:s");
    $row->visit_count++;
    }

    $row->save();

  }
}